<template>
  <el-dialog
    :model-value="true"
    :title="`${rowData.name} - 课程分配`"
    :close-on-click-modal="false"
    :before-close="handleClose"
    width="1200px"
  >
    <section class="table-box">
      <div class="left-box">
        <el-input
          class="input-name"
          placeholder="输入班级名称查询"
          @input="handelInput"
          :model-value="formData.name"
        >
          <template #prefix>
            <el-icon class="el-input__icon"><search /></el-icon>
          </template>
        </el-input>
        <p class="remark">点击表格数据，添加到结果表格中</p>
        <el-table
          :data="tableData"
          border
          size="small"
          @row-click="handleRowClick"
        >
          <el-table-column prop="name" label="课程名称"> </el-table-column>
          <el-table-column prop="category" label="类别"> </el-table-column>
          <el-table-column prop="paid_type" label="付费类型">
            <template #default="scope">
              <span>{{
                scope.row.paid_type == 0
                  ? "免费"
                  : scope.row.paid_type == 1
                  ? "付费"
                  : "限免"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格（元）"></el-table-column>
          <el-table-column prop="lecturer" label="讲师"></el-table-column>
        </el-table>
        <el-pagination
          :currentPage="formData.currentPage"
          :page-size="formData.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="right-box">
        <header class="header">结果表格，选中的课程将会最终分配。</header>
        <el-table :data="resultData" border size="small" ref="tableResultRef">
          <el-table-column type="selection"> </el-table-column>
          <el-table-column prop="name" label="课程名称"> </el-table-column>
          <el-table-column prop="category" label="类别"> </el-table-column>
          <el-table-column prop="paid_type" label="付费类型">
            <template #default="scope">
              <span>{{
                scope.row.paid_type == 0
                  ? "免费"
                  : scope.row.paid_type == 1
                  ? "付费"
                  : "限免"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格（元）"></el-table-column>
          <el-table-column prop="lecturer" label="讲师"></el-table-column>
          <el-table-column label="排序">
            <template #default="scope">
              <el-icon class="icon-arrow-up" v-if="scope.$index != 0"><ArrowUp @click="handleUp(scope.$index)" /></el-icon>
              <el-icon class="icon-arrow-down" v-if="scope.$index != resultData.length - 1"><ArrowDown @click="handleDown(scope.$index)" /></el-icon>
            </template>
          </el-table-column>
        </el-table>
        <footer class="footer">
          <el-button type="primary" @click="handleSubmit">确认</el-button>
          <el-button type="warning" @click="handleClose">取消</el-button>
        </footer>
      </div>
    </section>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineEmits, defineProps, watch, computed } from "vue";
import request from "@/utils/request";
import { Search } from "@element-plus/icons-vue";
// 引入页面需要用到的图标
import { ArrowUp, ArrowDown } from "@element-plus/icons-vue";

// 表单参数
const formData = reactive<any>({});

const emits = defineEmits(["close"]);

const props = defineProps({
  rowData: {
    type: Object,
  },
});

// 结果表格数据
const resultData = reactive<Array<object>>([]);

// 基础选择数据
const tableData = reactive<Array<object>>([]);

// 总行数
const total = ref(0);

/**
 * 调用axios，查询数据
 */
const handleQuery = (currentPage: number) => {
  formData.currentPage = currentPage;
  formData.pageSize = formData.pageSize || 20;
  request({
    url: "/course/queryListNotInClass",
    method: "POST",
    data: formData,
  }).then(({ data }) => {
    // 查询成功，将结果数据赋值到tableData中
    if (data.code > 0) {
      // 先清空再添加
      tableData.length = 0;
      // 将接口返回的数据数组，进行分析
      tableData.push(...data.data.list);
      // 将接口返回的总行数，赋值到total中，total传递到分页器组件中，会自动更新分页器组件中的数据
      total.value = data.data.total;
    }
  });
};

let timeoutId: any;

// 搜索方法：输入框内容变化时，触发，做了节流操作
const handelInput = (name: string) => {
  if (timeoutId) {
    clearTimeout(timeoutId);
  }
  formData.name = name;
  // 做一个节流
  timeoutId = setTimeout(() => {
    handleQuery(1);
  }, 1500);
};

const handleClose = () => {
  emits("close");
};

/**
 * 当前页变化
 * @param currentPage 当前页
 */
const handleCurrentChange = (currentPage: number) => {
  handleQuery(currentPage);
};

/**
 * 每页行数变化
 * @param pageSize 每页行数
 */
const handleSizeChange = (pageSize: number) => {
  formData.pageSize = pageSize;
  handleQuery(1);
};

const tableResultRef = ref();

/**
 * 点击搜索表格行，将数据移动到结果表格中
 */
const handleRowClick = (row: any, column: any, event: Event) => {
  // 从tableData中找到row的数据，然后从tableData中移除并加入到resultData中。
  const index = tableData.findIndex((v: any) => v.id == row.id);
  if (index >= 0) {
    // resultData中不存在该数据再加入
    if (!resultData.some((v: any) => v.id == row.id)) {
      const row2 = tableData.splice(index, 1)[0];
      resultData.push(row2);
      // 设置新增项默认选中
      tableResultRef.value.toggleRowSelection(row2, true);
    }
  }
};

// 进入页面之后查询课程
watch(
  () => props.rowData,
  (newVal) => {
    if (!newVal) {
      return;
    }
    resultData.length = 0;
    tableData.length = 0;
    formData.class_id = newVal.id;
    formData.name = "";
    request({
      url: `/course/queryListInClass/${newVal.id}`,
      method: "GET",
    }).then(({ data }) => {
      // 查询成功，将结果数据赋值到tableData中
      if (data.code > 0) {
        resultData.push(...data.data);
        // 设置默认选中
        tableResultRef.value.toggleAllSelection();
        handleQuery(1);
      }
    });
  },
  { immediate: true }
);

/**
 * 排序：向上移动一位，和前面的元素对换位置
 */
const handleUp = (index:number) => {
  resultData.splice(index - 1, 0, resultData.splice(index, 1)[0]);
}

/**
 * 排序：向下移动一位，和后面的元素对换位置
 */
const handleDown = (index:number) => {
  resultData.splice(index + 1, 0, resultData.splice(index, 1)[0]);
}

/**
 * 提交
 */
const handleSubmit = () => {
  const data = {
    class_id: props.rowData.id,
    course_ids: resultData.map((v: any) => v.id),
  };

  request({
    url: `/class/updateCourse`,
    method: "POST",
    data,
  }).then(({ data }) => {
    // 查询成功，将结果数据赋值到tableData中
    if (data.code > 0) {
      alert("分配课程成功");
      handleClose();
    }
  });
};
</script>

<style scoped lang="scss">

.el-dialog {

  .table-box {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .left-box {
      width: 50%;
      padding-right: 20px;

      .input-name {
        width: 100%;
      }

      .remark {
        padding: 5px 0px;
      }

      .el-table {
        height: 650px;
        width: 100%;
        margin-bottom: 5px;
      }
    }

    .right-box {
      width: 50%;

      .header {
        height: 58px;
        line-height: 58px;
      }

      .el-table {
        height: 650px;
        width: 100%;
        margin-bottom: 5px;

        .icon-arrow-up {
          color: var(--el-color-primary);
          margin-right: 15px;
          cursor: pointer;
        }

        .icon-arrow-down {
          color: var(--el-color-primary);
          cursor: pointer;
        }
      }

      .footer {
        display: flex;
        flex-direction: row-reverse;

        .el-button {
          margin: 0px 5px;
        }
      }
    }
  }
}
</style>